const express = require('express');
const path = require('path');
const fs = require('fs');
const http = require('http');
const app = express();

const request = require('request');

app.get(`/`, (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.get('/api', (req, res) => {
  var url_api = ['',''];
  var url = req.originalUrl.substring(req.originalUrl.indexOf("?"));
  url = url_api[0]+url;

  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1');
  res.header("Content-Type", "application/json;charset=utf-8");

  // res.send([
  //   {
  //     url: url,
  //     code: '200'
  //   },
  // ]);
  var token = req.query.token;
  if(token!="0123456789abcdefghijkl"){
      res.status(404).send('Not found');
  }else{
    request(url, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        res.send(body)
      }
    });
  }


});

app.get('/user/:id', (req, res) => {
  const id = req.params.id;
  res.send({
    id: id,
    title: 'serverless framework',
    link: 'https://serverless.com',
  });
});

app.get('/404', (req, res) => {
  res.status(404).send('Not found');
});

app.get('/500', (req, res) => {
  res.status(500).send('Server Error');
});

// Error handler
app.use(function (err, req, res, next) {
  console.error(err);
  res.status(500).send('Internal Serverless Error');
});

// 监听 9000 端口
app.listen(9000, () => {
  console.log(`Server start on http://localhost:9000`);
});
